package cn.ibobo.lease.app.service.impl;

import cn.ibobo.lease.app.dao.*;
import cn.ibobo.lease.common.dto.*;
import cn.ibobo.lease.app.service.UserCouponService;
import cn.ibobo.lease.common.base.BaseMapper;
import cn.ibobo.lease.common.base.BaseServiceImpl;
import cn.ibobo.lease.common.enums.ResultEnum;
import cn.ibobo.lease.common.util.DateUtil;
import cn.ibobo.lease.common.util.UuidUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.List;


/**
 * 用户点金券领用表业务处理接口
 * @Author lililiang
 * @Date 2018-12-13 18:36:40
 */
@Service
public class UserCouponServiceImpl extends BaseServiceImpl<UserCouponDTO, String> implements UserCouponService {

    private static final Log LOGGER = LogFactory.getLog(UserCouponServiceImpl.class);

    @Autowired
    private UserCouponMapper mapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private BusinessMapper businessMapper;


    @Override
    protected BaseMapper<UserCouponDTO, String> getMapper() {
        return mapper;
    }

    /**
     * 用户点金券领用表列表
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    public List<UserCouponDTO> list4Page(UserCouponDTO entity, Integer pageNum, Integer... pageSize) {
        return super.list4Page(entity, pageNum, pageSize);
    }

    /**
     * 用户点金券领用表列表（无分页）
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    public List<UserCouponDTO> listByCondition(UserCouponDTO entity) {
        return super.listByCondition(entity);
    }

    /**
     * 查询用户点金券领用表详情信息
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    public UserCouponDTO queryOneByPk(String id) {
        return super.queryOneByPk(id);
    }

    /**
     * 保存用户点金券领用表信息
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer save(UserCouponDTO entity) {
        String id = entity.getId();
        if(id == null || id.length() == 0){
            entity.setId(UuidUtil.getUuid());
            return mapper.add(entity);
        }else{
            return mapper.edit(entity);
        }
    }

    /**
     * 删除用户点金券领用表信息
     * @Author lililiang
     * @Date 2018-12-13 18:36:40
     * @Param
     * @Return
     */
    @Override
    @Transactional
    public Integer delete(String id) {
        return super.delete(id);
    }

    /**
     * @Description
     * @Author lililiang
     * @Date 2019/2/16 15:20
     * @Param [entityDTO]
     * @Return java.lang.Integer
     */
    @Transactional
    public Integer useCoupon(UserCouponDTO entityDTO) {
        //1. 用户点金账户减去使用点金金额
        entityDTO.setType(6);
        return this.coupon(entityDTO);
    }

    /**
     * @Description 增加点金券
     * @Author lililiang
     * @Date 2019/2/16 19:28
     * @Param [couponDTO]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer addCoupon(UserCouponDTO couponDTO){
        //1. 根据类型查询返还比例
        DictDTO dict = new DictDTO();
        dict.setMasterCode("coupon_ratio");
        List<DictDTO> dictDTOS = dictMapper.list4Page(dict);
        if(dictDTOS == null || dictDTOS.size() == 0){
            return ResultEnum.FAIL.getCode();
        }
        couponDTO.setMoney(couponDTO.getMoney().multiply(new BigDecimal(dictDTOS.get(0).getRemark().toString())));
        //2. 增加用户点金账户金额
        UserDTO user = new UserDTO();
        user.setUid(couponDTO.getUid());
        user.setCoupon(couponDTO.getMoney());
        user.setType((byte)1);
        if(userMapper.coupon(user) <= 0){
            return ResultEnum.FAIL.getCode();
        }
        //3. 增加点金记录
        return mapper.add(couponDTO);
    }

    /**
     * @Description 增加减少点金券
     * @Author lililiang
     * @Date 2019/2/16 15:20
     * @Param [entityDTO]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer coupon(UserCouponDTO entityDTO) {
        //1. 用户点金账户减去使用点金金额
        UserDTO user = new UserDTO();
        user.setUid(entityDTO.getUid());
        user.setCoupon(entityDTO.getMoney());
        if(entityDTO.getType() == 6){//6线下购物使用
            //线下购物时，需要根据加盟店折扣比例，计算总金额，并保存到点金记录中
            BusinessDTO businessDTO = businessMapper.queryOneByPk(entityDTO.getBid());
            if(businessDTO != null && businessDTO.getRatio() != null){
                entityDTO.setRatio(businessDTO.getRatio());
                entityDTO.setTotalMoney(entityDTO.getMoney().divide(businessDTO.getRatio()));
            }
            user.setType((byte)2);//减少
        }else{
            user.setType((byte)1);
        }
        if(userMapper.coupon(user) <= 0){
            return ResultEnum.NO_ENOUGH_COUPON.getCode();
        }
        //2. 增加点金记录
        entityDTO.setId(UuidUtil.getUuid());
        entityDTO.setCreatetm(DateUtil.getNow());
        return mapper.add(entityDTO);
    }

    /**
     * @Description 用户领取点金券
     * @Author lililiang
     * @Date 2019/2/20 20:00
     * @Param [entityDTO]
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public Integer getCoupon(UserCouponDTO entityDTO){
        //0. 校验用户是否领用过点金券
        List<UserCouponDTO> userCouponDTOS = mapper.listByCondition(entityDTO);
        if(userCouponDTOS != null && userCouponDTOS.size() > 0){
            return ResultEnum.HAS_GOT_COUPON.getCode();
        }
        //1. 校验点金券是否有剩余数量，同时减一
        if(couponMapper.subOne(entityDTO.getCid()) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.NO_COUPON.getCode();
        }
        //2. 用户增加点金金额
        CouponDTO couponDTO = couponMapper.queryOneByPk(entityDTO.getCid());
        UserDTO user = new UserDTO();
        user.setUid(entityDTO.getUid());
        user.setCoupon(couponDTO.getMoney());
        user.setType((byte)1);
        if(userMapper.coupon(user) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.NO_ENOUGH_COUPON.getCode();
        }
        //3. 增加点金记录
        entityDTO.setId(UuidUtil.getUuid());
        entityDTO.setCreatetm(DateUtil.getNow());
        entityDTO.setMoney(couponDTO.getMoney());
        entityDTO.setType(0);
        if(mapper.add(entityDTO) <= 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultEnum.FAIL.getCode();
        }
        return ResultEnum.SUCCESS.getCode();
    }
}
